import { useRef, useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Anchor } from 'antd'

type PropsType = {
  list: Array<Category>
  container?: HTMLElement
  bounds?: number
}

export default function AnchorBar({ list, container, bounds = 40 }: PropsType) {
  const anchorContainerRef = useRef<HTMLElement>()
  const [containerHeight, setContainerHeight] = useState(0)

  // 计算锚点容器高度
  const computedHeight = () => setContainerHeight(anchorContainerRef.current?.offsetHeight || 0)
  // 窗口大小改变
  window.onresize = () => computedHeight()

  useEffect(() => {
    computedHeight()
  })

  return (
    <div className='anchor-container' ref={anchorContainerRef as React.LegacyRef<HTMLDivElement>}>
      {list.length ? (
        <Anchor
          className={styles['anchor-bar']}
          getCurrentAnchor={activeLink => activeLink || `#${list[0].categoryNameEn}`}
          getContainer={() => container || window}
          bounds={bounds}
          targetOffset={containerHeight}>
          {list.map(item => (
            <Anchor.Link key={item.id} href={`#${item.categoryNameEn}`} title={item.categoryNameZh} />
          ))}
        </Anchor>
      ) : null}
    </div>
  )
}
